package com.qiyuesuo.server.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 获得数据库连接，释放连接
 *
 * @author s77
 * @create 2020-4月-01 12:59
 */
public class DbUtil {
    private final static Logger logger = LoggerFactory.getLogger(DbUtil.class);
    private static final String DB_URL = "jdbc:derby:file_download_upLoad;create=true";
    private static final String JDBC_DRIVER = "org.apache.derby.jdbc.EmbeddedDriver";

    /*
     * 获取数据库连接
     */
    public static Connection getConnection() {
        Connection con = null;
        try {
            // 注册JDBC驱动
            Class.forName(JDBC_DRIVER);
            // 打开连接
            con = DriverManager.getConnection(DB_URL);
        } catch (Exception e) {  // 处理Class.forName的类找不到错误
            logger.error("数据库驱动加载失败，无法连接", e);
        }
        return con;
    }

    /*
     * 关闭数据库连接
     */
    public static void closeConnection(Connection con) {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                logger.error("数据库连接关闭失败", e);
            }
        }
    }
}

